import Vue from 'vue'
import Vuex from 'vuex'
import { login } from '../api/request'
import persistedState from 'vuex-persistedstate'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    adminId: '',
    groupType: '', // 角色
    level: '', // 等级
    groupId: '', // 角色id
    auth: '', // 加密
    area: '', // 辖区
    isAssign: '' // 是否分配账号
  },
  mutations: {
    SET_ADMINID: (state, adminId) => {
      state.adminId = adminId
    },
    SET_GROUPTYPE: (state, groupType) => {
      state.groupType = groupType
    },
    SET_IS_ADMINISTRATOR:(state,is_administrator)=>{
      state.is_administrator = is_administrator
    },
    SET_GROUPID: (state, groupId) => {
      state.groupId = groupId
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_PARKING_LOT_ID: (state, parking_lot_id) => {
      state.parking_lot_id = parking_lot_id
    },
    SET_VUEAUTHLIST: (state, vueAuthList) => {
      state.vueAuthList = vueAuthList
    }
  },
  actions: {
    login ({ commit }, userInfo) {
      const { username, password } = userInfo
      return new Promise((resolve, reject) => {
        login({ username: username, password: password }).then(res => {
          commit('SET_ADMINID', res.admin_id)
          commit('SET_GROUPTYPE', res.group_type)
          commit('SET_IS_ADMINISTRATOR', res.is_administrator)
          commit('SET_PARKING_LOT_ID', res.parking_lot_id)
          commit('SET_VUEAUTHLIST', res.vueAuthList)
          commit('SET_GROUPID', res.group_id)
          commit('SET_TOKEN', res.token)
          sessionStorage.setItem('userInfo', JSON.stringify(res))
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    logout ({ commit }) {
      commit('SET_ADMINID', '') 
    }
  },
  modules: {
  },
  plugins: [persistedState()]
})
